package com.sxz.mall.product.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sxz.mall.common.constant.ProductConstant;
import com.sxz.mall.common.dto.MemberPrice;
import com.sxz.mall.common.dto.SkuHasStockDto;
import com.sxz.mall.common.dto.SkuReductionDTO;
import com.sxz.mall.common.dto.SpuBoundsDTO;
import com.sxz.mall.common.dto.es.SkuESModel;
import com.sxz.mall.common.utils.R;
import com.sxz.mall.product.entity.*;
import com.sxz.mall.product.feign.CouponFeignService;
import com.sxz.mall.product.feign.SearchFeignService;
import com.sxz.mall.product.feign.WareSkuFeignService;
import com.sxz.mall.product.service.*;
import com.sxz.mall.product.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxz.mall.common.utils.PageUtils;
import com.sxz.mall.common.utils.Query;

import com.sxz.mall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuImagesService spuImagesService;
    @Autowired
    SpuInfoDescService spuInfoDescService;
    @Autowired
    AttrService attrService;
    @Autowired
    ProductAttrValueService productAttrValueService;
    @Autowired
    SkuInfoService skuInfoService;
    @Autowired
    SkuImagesService skuImagesService;
    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    CategoryService categoryService;
    @Autowired
    BrandService brandService;

    @Autowired
    WareSkuFeignService wareSkuFeignService;

    @Autowired
    SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 保存商品的发布信息   多多表
     *
     * @param spuInfoVo
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuInfoVO spuInfoVo) {
        // 1、保存spu基本信息pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuInfoVo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.save(spuInfoEntity);

        // 2、保存spu描述信息pms_spu_info_desc 图
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",", spuInfoVo.getDecript()));
        spuInfoDescService.save(spuInfoDescEntity);
        // 3、保存图集信息 pms_spu_images
        List<SpuImagesEntity> spuImages = spuInfoVo.getImages().stream().map(item -> {
            SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
            spuImagesEntity.setSpuId(spuInfoEntity.getId());
            spuImagesEntity.setImgUrl(item);
            return spuImagesEntity;
        }).collect(Collectors.toList());
        spuImagesService.saveBatch(spuImages);

        // 4、保存规格参数 pms_product_attr_value
        List<ProductAttrValueEntity> attrValueEntities = spuInfoVo.getBaseAttrs().stream().map(item -> {
            ProductAttrValueEntity attrValueEntity = new ProductAttrValueEntity();
            attrValueEntity.setSpuId(spuInfoEntity.getId());
            attrValueEntity.setAttrId(item.getAttrId());
            attrValueEntity.setAttrValue(item.getAttrValues());
            attrValueEntity.setAttrName(attrService
                    .getById(item.getAttrId()).getAttrName());
            attrValueEntity.setQuickShow(item.getShowDesc());
            return attrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(attrValueEntities);
        // 5、保存对应的sku信息
        List<Skus> skus = spuInfoVo.getSkus();
        if (skus != null && skus.size() > 0) {
            // 5.1保存sku基本信息：pms_sku_info
            skus.forEach(item -> {
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSaleCount(0L);
                String defaultImg = "";
                List<Images> images1 = item.getImages();

                for (Images image : images1) {
                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();
                    }
                }
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.save(skuInfoEntity);
                // 5.2批量保存sku图片：pms_sku_image
                List<SkuImagesEntity> skuImagesEntityList = images1.stream().map(image -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                    skuImagesEntity.setImgUrl(image.getImgUrl());
                    skuImagesEntity.setDefaultImg(image.getDefaultImg());
                    return skuImagesEntity;
                }).filter(img -> {
                    return img.getDefaultImg() == 1;
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesEntityList);
                // 5.4sku销售属性信息pms_sku_sale_attr_value
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntityList = item.getAttr().stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntityList);

                // 5.3保存满减信息，折扣，会员价mall_sms:sms_sku_ladder  sms_full_reduction sms_member_price
                // dto（数据传输对象）传输到service进行feign处理
                SkuReductionDTO dto = new SkuReductionDTO();
                BeanUtils.copyProperties(item, dto);
                dto.setSkuId(skuInfoEntity.getSkuId());
                if (item.getMemberPrice() != null && item.getMemberPrice().size() > 0) {
                    List<MemberPrice> memberPriceList = item.getMemberPrice().stream().map(price -> {
                        MemberPrice memberPrice = new MemberPrice();
                        BeanUtils.copyProperties(price, memberPrice);
                        return memberPrice;
                    }).collect(Collectors.toList());
                    dto.setMemberPrice(memberPriceList);
                }
                R r = couponFeignService.saveFullReductionInfo(dto);
                if (r.getCode() != 0) {
                    log.error("调用Couppon服务处理满减、折扣、会员价操作失败....");
                }
            });
        }


        // 6、保存spu的积分信息：mall-sms：sms_spu_bounds
        Bounds bounds = spuInfoVo.getBounds();
        SpuBoundsDTO spuBoundsDTO = new SpuBoundsDTO();
        BeanUtils.copyProperties(bounds, spuBoundsDTO);
        spuBoundsDTO.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.save(spuBoundsDTO);
        if (r.getCode() != 0) {
            log.error("调用couppon服务存储积分信息失败");
        }
    }

    /**
     * 信息检索 复杂
     * 分类，品牌，状态，关键字
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByConditions(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and(w -> {
                w.eq("id", key)
                        .or()
                        .like("spu_name", key)
                        .like("spu_description", key);
            });
        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            wrapper.eq("publish_status", status);
        }
        String catalogId = (String) params.get("catalogId");
        if (!StringUtils.isEmpty(catalogId) && !"0".equalsIgnoreCase(catalogId)) {
            wrapper.eq("catalog_id", catalogId);
        }

        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            wrapper.eq("brand_id", brandId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        List<SpuInfoVO> spuInfoVOList = page.getRecords().stream().map(item -> {
            CategoryEntity categoryEntity = categoryService.getById(item.getCatalogId());
            BrandEntity brandEntity = brandService.getById(item.getBrandId());
            SpuInfoVO spuInfoVO = new SpuInfoVO();
            BeanUtils.copyProperties(item, spuInfoVO);
            spuInfoVO.setCatalogName(categoryEntity.getName());
            spuInfoVO.setBrandName(brandEntity.getName());
            return spuInfoVO;
        }).collect(Collectors.toList());

        IPage<SpuInfoVO> ipage = new Page<SpuInfoVO>();
        ipage.setRecords(spuInfoVOList);
        ipage.setPages(page.getPages());
        ipage.setCurrent(page.getCurrent());

        return new PageUtils(ipage);
    }

    /**
     * 查询信息，封装对象
     * 调用mall-search，存储到es
     * 更新spuId对应的上架状态
     *
     * @param spuId
     */
    @Override
    public void up(Long spuId) {
//        1、获取数据封装到SkuEsModul
//        List<SkuESModel> skuEs = new ArrayList<>();

        List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuId(spuId);

        // 对应的规格参数，每个都会有，避免重复, attr中的searchType，有条件，是否可以检索，需要过滤
        List<SkuESModel.Attrs> attrsModel = getAttrsModel(spuId);

        // 远程调用获取库存信息，一次获取所有，批量查询
        List<Long> skuIds = skus.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
        Map<Long, Boolean> skuHasStockMap = getSkuHasStock(skuIds);

        List<SkuESModel> skuESModels = skus.stream().map(item -> {
            SkuESModel skuESModel = new SkuESModel();
            BeanUtils.copyProperties(item, skuESModel);
            skuESModel.setSubTitle(item.getSkuTitle());
            skuESModel.setSkuPrice(item.getPrice());
            // 是否有库存，跨系统查询
            if (skuHasStockMap == null) {
                skuESModel.setHasStock(true);
            } else {
                skuESModel.setHasStock(skuHasStockMap.get(item.getSkuId()));
            }
            //热度分 默认0
            skuESModel.setHotScore(0L);
            // 名称等
            BrandEntity brand = brandService.getById(item.getBrandId());
            CategoryEntity category = categoryService.getById(item.getCatalogId());
            skuESModel.setBrandName(brand.getName());
            skuESModel.setBrandImg(brand.getLogo());
            skuESModel.setCatalogName(category.getName());

            // 存储attrs
            skuESModel.setAttrs(attrsModel);

            return skuESModel;
        }).collect(Collectors.toList());

        // 存储到es
        R r = searchFeignService.productStatusUp(skuESModels);
        if (r.getCode() == 0) {
            baseMapper.updateSpuStatusUp(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        } else {
            // 远程调用失败
        }

    }

    @Override
    public List<OrderItemSpuInfoVO> getOrderItemSpuInfoByIds(Long[] spuIds) {
        List<OrderItemSpuInfoVO> list = new ArrayList<>();
        for (Long spuId : spuIds) {
            OrderItemSpuInfoVO itemVO = new OrderItemSpuInfoVO();
            SpuInfoEntity entity = this.getById(spuId);
            itemVO.setId(entity.getId());
            itemVO.setSpuName(entity.getSpuName());
            itemVO.setBrandId(entity.getBrandId());
            itemVO.setCatalogId(entity.getCatalogId());
            // 品牌信息
            BrandEntity brandEntity = brandService.getById(entity.getBrandId());
            itemVO.setBrandName(brandEntity.getName());
            // 分类信息
            CategoryEntity categoryEntity = categoryService.getById(entity.getCatalogId());
            itemVO.setCatalogName(categoryEntity.getName());

            list.add(itemVO);
        }
        return list;
    }

    // 处理list为map形式
    private Map<Long, Boolean> getSkuHasStock(List<Long> skuIds) {
        List<SkuHasStockDto> skusHasStock = null;
        if (skuIds == null || skuIds.size() == 0) {
            return null;
        }
        try {
            skusHasStock = wareSkuFeignService.getSkusHasStock(skuIds);
            Map<Long, Boolean> map = skusHasStock.stream().collect(Collectors.toMap(item -> {
                return item.getSkuId();
            }, item -> {
                return item.getHasStock();
            }));

            return map;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private List<SkuESModel.Attrs> getAttrsModel(Long spuId) {
        List<ProductAttrValueEntity> baseAttrs = productAttrValueService.getAttrsBySpuId(spuId);
        List<Long> attrIds = baseAttrs.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        // 过滤出允许检索的baseAttrs
        List<Long> searchAttrIds = attrService.selectSearchAttrIds(attrIds);
        List<SkuESModel.Attrs> attrsModel = baseAttrs.stream().filter(item -> {
            return searchAttrIds.contains(item.getAttrId());
        }).map(item -> {
            SkuESModel.Attrs attr = new SkuESModel.Attrs();
            BeanUtils.copyProperties(item, attr);
            return attr;
        }).collect(Collectors.toList());
        return attrsModel;
    }

}